import { Button, Card, message, Table, Form, Row, Col, Input, Select } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import Ellipsis from '../../../components/Ellipsis';
import { PlusOutlined } from '@ant-design/icons';
import AddModal from './addModal';
import EditModal from './editModal';
import styles from '../../../components/common/PateoTable/TableList.less';
import * as G from '../../../utils/common';
import { filterAuth } from '@/support/common';
import MaskText from '@/components/MaskText';

const WarningShowTypeHash = {
  1: '弱提醒',
  2: '弹窗提醒',
  3: '霸屏提醒',
};
const IsEnableHash = {
  0: '未生效',
  1: '已生效',
  2: '已停用',
};
const UseTypeHash = {
  1: '跛行',
  2: '锁车',
  3: '其他',
};

class DeviceWarningRules extends PureComponent {
  state = {
    addModalVisible: false,
    editModalVisible: false,
    editModalData: null,
    tableData: [],
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableLoading: false,
    formValues: {},
  };

  componentDidMount() {
    this.handleTableData();
    const { dispatch } = this.props;
    dispatch({
      type: 'menu/getMerchantsData',
    });
  }

  handleTableData = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.props.dispatch({
      type: 'deviceWarningRules/postFetchPage',
      payload: {
        url: '/mscreditbusiness/iviNotice/page',
        ...formValues,
      },
    });
  };

  handleEdit = (record) => {
    this.setState({
      editModalVisible: true,
      editModalData: record,
    });
  };
  handleDelete = (uuid) => {
    this.props.dispatch({
      type: 'deviceWarningRules/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/iviNotice/delete',
        uuid,
      },
      callback: (response) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };
  handleIsEnable = (uuid, isEnable) => {
    this.props.dispatch({
      type: 'deviceWarningRules/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/iviNotice/isEnable',
        uuid,
        isEnable,
      },
      callback: (response) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
          // } else {
          //   message.error(response.statusMessage);
        }
      },
    });
  };

  handleAdd = () => {
    this.setState({
      addModalVisible: true,
    });
  };

  changeAddModalVisible = (flag) => {
    if (flag) {
      this.handleTableData();
      this.setState({
        addModalVisible: false,
      });
    } else {
      this.setState({
        addModalVisible: false,
      });
    }
  };

  changeEditModalVisible = (flag) => {
    if (flag) {
      this.handleTableData();
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    } else {
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    }
  };

  render() {
    const { addModalVisible, editModalVisible, editModalData, formValues } = this.state;
    const {
      deviceWarningRules: {
        pageData: { rows, pagination },
      },
      loading,
      dispatch,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    const searchItems = [
      {
        type: 'input',
        title: '告警规则名称',
        key: 'name',
      },
      {
        type: 'select',
        title: '告警显示方式',
        key: 'showType',
        selectOptions: [
          { value: '1', label: '弱提醒' },
          { value: '2', label: '弹窗提醒' },
          { value: '3', label: '霸屏提醒' },
        ],
      },
      {
        type: 'select',
        title: '是否开启TTS语音播报',
        key: 'ttsVoiceFlag',
        selectOptions: [
          { value: '0', label: '不开启' },
          { value: '1', label: '开启' },
        ],
      },
      {
        type: 'select',
        title: '生效状态',
        key: 'isEnable',
        selectOptions: [
          { value: '0', label: '未生效' },
          { value: '1', label: '已生效' },
          { value: '2', label: '已停用' },
        ],
      },
      {
        type: 'input',
        title: '创建人',
        key: 'createBy',
      },
      //  {
      //    type: 'select',
      //    title: '使用场景',
      //    key: 'useType',
      //    selectOptions: [
      //      { value: '1', label: '跛行' },
      //      { value: '2', label: '锁车' },
      //      { value: '3', label: '其他' },
      //    ],
      //  },
    ];
    const editBtnAuth = filterAuth('deviceWarningRules-edit', permissions, pathname);
    const deleteBtnAuth = filterAuth('deviceWarningRules-del', permissions, pathname);
    const enableBtnAuth = filterAuth('deviceWarningRules-enable', permissions, pathname);
    const disableBtnAuth = filterAuth('deviceWarningRules-disable', permissions, pathname);

    const columns = [
      {
        title: '告警规则名称',
        dataIndex: 'name',
        render: (text, record) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '使用场景',
        dataIndex: 'useType',
        render: (text) => UseTypeHash[text],
      },
      {
        title: '标题',
        dataIndex: 'warnTitle',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '告警显示方式',
        dataIndex: 'showType',
        render: (text) => WarningShowTypeHash[text],
      },
      {
        title: '告警内容',
        dataIndex: 'warnContent',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '是否开启TTS语音播报',
        dataIndex: 'ttsVoiceFlag',
        render: (text) => {
          return text ? '开启' : '不开启';
        },
      },
      {
        title: 'TTS语音播报内容',
        dataIndex: 'ttsContent',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '生效状态',
        dataIndex: 'isEnable',
        render: (text) => IsEnableHash[text],
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text) => {
          if (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss');
          }
        },
      },
      {
        title: '操作',
        dataIndex: 'uuid',
        fixed: 'right',
        render: (text, record) => {
          const btns = [];
          const editBtn = {
            title: '修改',
            key: 'edit',
            auth: 'deviceWarningRules-edit',
            onConfirm: () => this.handleEdit(record),
          };
          const editConfirmBtn = {
            title: '修改',
            Popconfirm: true,
            message: '该告警规则可能已经被使用，确认要修改吗？',
            key: 'editComfirm',
            auth: 'deviceWarningRules-edit',
            onConfirm: () => this.handleEdit(record),
          };
          const editUsedConfirmBtn = {
            title: '修改',
            Popconfirm: true,
            message: '该告警规则已被使用，确认要修改吗？',
            key: 'editUsedConfirm',
            auth: 'deviceWarningRules-edit',
            onConfirm: () => this.handleEdit(record),
          };
          const deleteBtn = {
            title: '删除',
            Popconfirm: true,
            message: '确认要删除吗?',
            key: 'delete',
            auth: 'deviceWarningRules-del',
            onConfirm: () => this.handleDelete(text),
          };
          const enableBtn = {
            title: '启用',
            Popconfirm: true,
            message: '确认要启用吗?',
            key: 'enable',
            auth: 'deviceWarningRules-enable',
            onConfirm: () => this.handleIsEnable(text, 1),
          };
          const disableBtn = {
            title: '停用',
            Popconfirm: true,
            message: '确认要停用吗?',
            key: 'disable',
            auth: 'deviceWarningRules-disable',
            onConfirm: () => this.handleIsEnable(text, 2),
          };
          // 非系统预设
          if (!record.isSystem) {
            if (record.isEnable === 0) {
              // 未生效 - 删除 修改 启用
              btns.push(deleteBtn);
              // btns.push(editConfirmBtn);
              btns.push(enableBtn);
              btns.push(editBtn);
            } else if (record.isEnable === 1) {
              // if (record.isUsed === 1) {
              //   // 生效 & 使用 - 确认修改
              btns.push(editConfirmBtn);
              // } else {
              //   // 生效 & 未使用 - 修改
              //   if (editBtnAuth) btns.push(editBtn);
              // }
              // 生效 - 不为系统预设的 可停用
              if (!record.isSystem) btns.push(disableBtn);
            } else if (record.isEnable === 2) {
              // 已停用 - 启用
              btns.push(enableBtn);
              if (record.isUsed === 1) {
                // 已停用 & 使用 - 确认修改
                btns.push(editUsedConfirmBtn);
              } else {
                // 已停用 & 未使用 - 修改
                btns.push(editBtn);
              }
            }
          } else {
            //  预设规则操作区只有修改按钮
            btns.push(editBtn);
          }
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: rows,
      loading,
      rowKey: (record) => record.uuid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'deviceWarningRules/postFetchPage',
              url: '/mscreditbusiness/iviNotice/page',
            }}
            dispatch={dispatch}
            saveFormValues={(val) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>

        {/* <div className={styles.tableListForm}>
            <Form onSubmit={this.handleSearch} layout="inline">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24} key="name">
                  <FormItem key="name" label="告警规则名称">
                    {getFieldDecorator('name')(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} key="showType">
                  <FormItem key="showType" label="告警显示方式">
                    {getFieldDecorator('showType')(
                      <Select placeholder="请选择" allowClear>
                        <Option value={1}>弱提醒</Option>
                        <Option value={2}>弹窗提醒</Option>
                        <Option value={3}>霸屏提醒</Option>
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} key="ttsVoiceFlag">
                  <FormItem key="ttsVoiceFlag" label="是否开启TTS语音播报">
                    {getFieldDecorator('ttsVoiceFlag')(
                      <Select placeholder="请选择" allowClear>
                        <Option value={0}>不开启</Option>
                        <Option value={1}>开启</Option>
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} key="isEnable">
                  <FormItem key="isEnable" label="生效状态">
                    {getFieldDecorator('isEnable')(
                      <Select placeholder="请选择" allowClear>
                        <Option value={0}>未生效</Option>
                        <Option value={1}>已生效</Option>
                        <Option value={2}>已停用</Option>
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} key="createBy">
                  <FormItem key="createBy" label="创建人">
                    {getFieldDecorator('createBy')(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} key="useType">
                  <FormItem key="useType" label="使用场景">
                    {getFieldDecorator('useType')(
                      <Select placeholder="请选择" allowClear>
                        <Option value={1}>跛行</Option>
                        <Option value={2}>锁车</Option>
                        <Option value={3}>其他</Option>
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}></Col>
                <Col md={8} sm={24}></Col>
                <Col md={8} sm={24}>
                  <span
                    style={{
                      display: 'block',
                      width: '100%',
                      textAlign: 'right',
                    }}
                  >
                    <Button type="primary" onClick={(e) => this.handleSearch(e)}>
                      查询
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                      重置
                    </Button>
                  </span>
                </Col>
              </Row>
            </Form>
          </div> */}
        <Card className={styles.standardTable}>
          {filterAuth('deviceWarningRules-add', permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新建规则
              </Button>
            </div>
          ) : null}

          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'deviceWarningRules/postFetchPage',
              url: '/mscreditbusiness/iviNotice/page',
            }}
            formValues={formValues}
          />
        </Card>
        {addModalVisible ? <AddModal changeAddModalVisible={this.changeAddModalVisible} /> : null}
        {editModalVisible ? (
          <EditModal
            editModalData={editModalData}
            changeEditModalVisible={this.changeEditModalVisible}
          />
        ) : null}
      </div>
    );
  }
}
export default connect((state) => {
  return {
    common: state.common,
    loading: state.loading.effects['deviceWarningRules/postFetchPage'],
    permissions: state?.menu?.permissions,
    deviceWarningRules: state.deviceWarningRules,
  };
})(DeviceWarningRules);
